package com.tim.shadow.lib.image;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.SoftReference;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Rect;

import com.tim.shadow.lib.util.MD5;

/*
 * Author: poper Email:xut@bluemobi.cn
 * Created Date:2013-4-17
 * Copyright @ 2013 BU
 * Description: 类描述
 *
 * History:
 */
public class TImageGetter {

	public static Bitmap getReferenceImage(Context context, String url) {
		return null;
	}

	public static Bitmap getLocalImage(Context context, String url) {
		File file = context.getExternalCacheDir();
		if (null == file) {// SDCard是否存在
			return null;
		}
		File imageFile = new File(file, MD5.Md5(url) + ".png");// 用于获取图片的绝对路径
		Bitmap b = null;
		if (imageFile.exists()) {
			b = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
		}
		if (null != b) {
			((TImageApplication) context.getApplicationContext())
					.getImageCache().getmBitmapCache()
					.put(MD5.Md5(url), new SoftReference<Bitmap>(b));
		}
		return b;
	}

	public static Bitmap getNetImage(Context context, String url) {
		System.out.println(url);
		HttpClient client = new DefaultHttpClient();
		Bitmap b = null;
		HttpGet get = new HttpGet(url);
		try {
			HttpResponse response = client.execute(get);
			if (response.getStatusLine().getStatusCode() == 200) {
				BitmapFactory.Options o = new BitmapFactory.Options();
				o.inSampleSize = 2;
				b = BitmapFactory.decodeStream(response.getEntity()
						.getContent(), new Rect(), o);
				File file = context.getExternalCacheDir();
				if (!file.exists()) {
					file.mkdirs();
				}
				File picFile = new File(file, MD5.Md5(url) + ".png");
				FileOutputStream out = new FileOutputStream(picFile);
				if (null != b && null != out) {
					b.compress(CompressFormat.JPEG, 100, out);
				}
				out.close();
				if (null != b) {
					((TImageApplication) context.getApplicationContext())
							.getImageCache().getmBitmapCache()
							.put(MD5.Md5(url), new SoftReference<Bitmap>(b));
				}
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return b;
	}
}
